import { getRandomId } from '../utils/helper';

function makeCache(store) {
  const setCache = (v, k = getRandomId(16)) => {
    store.commit('setCache', { k, v });
    return k;
  };

  const cache = Object.freeze({
    get: k => {
      const v = store.state.cache[k];
      if (v && v.once) cache.delete(k);
      return v && v.value;
    },
    setOnce: value => setCache({ value, once: true }),
    set: value => setCache({ value }),
    update: (k, value) => setCache({ value }, k),
    updateOnce: (k, value) => setCache({ value, once: true }, k),
    delete: k => {
      store.commit('deleteCache', { k });
    },
    clear: () => {
      store.commit('clearCache');
    }
  });
  return cache;
}

export default makeCache;
